<template>
	<view class="container">
		<view class="avatar-wrap">
			<button class="u-reset-button" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
				<u-avatar :src="$utils.imgPath(userForm.avatar)" size="130rpx"></u-avatar>
				<q-upload style="display: none;" ref="aliossUpload" :token="token" />
			</button>
		</view>
		<u--form labelPosition="left" labelWidth="150rpx">
			<u-form-item label="昵称" borderBottom>
				<input v-model="userForm.nickname" placeholder="请输入昵称" type="nickname" @change="nicknameChange" />
			</u-form-item>
			<u-form-item label="性别" borderBottom @click="showSex = true;">
				<u--input v-model="userGender" disabled disabledColor="#ffffff" placeholder="请选择性别" border="none">
				</u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>
		</u--form>
		<view style="margin-top: 50rpx;">
			<u-button @click="onSubmit" type="primary" shape="circle" text="保存信息"></u-button>
		</view>

		<!-- 性别选择器 -->
		<u-action-sheet :show="showSex" :actions="sexActions" title="请选择性别" @close="showSex = false"
			@select="sexSelect">
		</u-action-sheet>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				showSex: false,
				schoolName: '',
				sexActions: [{
						value: 1,
						name: '男生',
					},
					{
						value: 2,
						name: '女生',
					}
				],
				userForm: {
					avatar: '',
					nickname: '',
					sex: 0
				},
				userGender: ''
			};
		},
		computed: {
			userInfo() {
				return this.$store.state.userInfo;
			}
		},
		onShow() {
			this.userForm.avatar = this.userInfo.avatar;
			// this.userForm.nickname = this.userInfo.nickname;
		},
		methods: {
			onSubmit() {
				if (!this.userForm.avatar) {
					uni.showToast({
						icon: 'none',
						title: "请上传头像"
					})

					return;
				}

				if (!this.userForm.nickname) {
					uni.showToast({
						icon: 'none',
						title: "请填写昵称"
					})

					return;
				}


				if (!this.userForm.sex) {
					uni.showToast({
						icon: 'none',
						title: "请选择性别"
					})

					return;
				}

				uni.showLoading({
					mask: true,
					title: "正在保存..."
				})

				this.$H.post('user/updateUser', this.userForm).then(res => {
					if (res.code == 1) {
						uni.switchTab({
							url: "/pages/index/index"
						})
					}
					uni.hideLoading();
				});
			},
			onChooseAvatar(e) {
				let that = this;
				const avatarUrl = e.detail.avatarUrl;
				wx.cropImage({
					src: avatarUrl,
					cropScale: '1:1',
					success: async (res) => {
						let aliossUpload = that.$refs.aliossUpload;
						that.userForm.avatar = await aliossUpload.uploadFilePromise(res.tempFilePath);
					}
				})
			},
			nicknameChange(e) {
				this.userForm.nickname = e.detail.value;
			},
			sexSelect(e) {
				this.userForm.sex = e.value;
				this.userGender = e.name;
			}
		}
	}
</script>

<style lang="scss" scoped>
	.u-reset-button {
		margin: 0;
	}

	.avatar-wrap {
		display: flex;
		height: 260rpx;
		justify-content: center;
		align-items: center;
	}
</style>